<template>
  <el-dialog v-model="dialogVisible" title="监控详情" width="900" append-to-body @close="closeDialog">
    <el-row :gutter="10">
      <el-col :span="6">
        <div>
          <el-input
            class="search-input"
            placeholder="请输入关键字"
            :prefix-icon="Search"
            v-model="searchKey"
            size="small"
          >
          </el-input>
        </div>
        <div class="tree-content">
          <el-tree
            :data="treeData"
            node-key="id"
            :props="{
              children: 'children',
              label: 'areaName',
              // label: 'pinyin',
            }"
            :expand-on-click-node="false"
            default-expand-all
            ref="mineTreeRef"
            :filter-node-method="filterNode"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node" @click="mineClick(data)">
                <span class="node-text" :title="node.label">
                  {{ node.label }}
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="18">
        <div class="video-div">
          <el-row :gutter="5">
            <el-col :span="12" v-for="(item, index) in videoList" :key="index" class="video-child">
              <div class="video-child-name">{{ item.deviceName }}</div>
              <video :id="item.id" :src="item.videoUrl" style="width: 100%;height: 200px;" muted controls="true"></video>
            </el-col>
          </el-row>
        </div>
        <div class="page-div">
          <el-pagination 
            v-model:current-page="queryParams.pageNum"
            background 
            layout="total, prev, pager, next" 
            :total="total"
            :page-size="queryParams.pageSize"
            @change="onPagechange"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import { getmineTree } from "@/api";
import useUserStore from "@/store/modules/user";
import { getMineInfoById, getMonitorByMine } from "@/api/situation";
import { nextTick } from "vue";
import flvjs from "flv.js";
const { proxy } = getCurrentInstance();
const dialogVisible = ref(false);
const searchKey = ref("");
const loading = ref(false);
const treeData = ref([]);
const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 4,
  openPitNo: ''
})
const videoList = ref([
  {videoName:'宝宏1号', videoUrl:'http://218.23.184.226:8050/live/34020000001110000004_34020000001320000001.flv?sid=0', id:'sj1'},
  {videoName:'宝宏2号', videoUrl:'http://218.23.184.226:8050/live/34020000001110000004_34020000001320000003.flv?sid=0', id:'sj2'},
  {videoName:'龙跃1号', videoUrl:'http://111.38.126.130:8050/live/34020000001110000004_34020000001320000001.flv?sid=0', id:'sj3'},
  {videoName:'龙跃2号', videoUrl:'http://111.38.126.130:8050/live/34020000001110000004_34020000001320000010.flv?sid=0', id:'sj4'},
])
// 存储flv播放器实例的对象
const flvPlayers = ref([]);
let sourceList;
watch(searchKey, (val) => {
  proxy.$refs["mineTreeRef"].filter(val);
});

function loadTree() {
  loading.value = true;
  const params = { minTree: false };
  getmineTree(params).then((res) => {
    let { areaId, roles } = useUserStore().userInfo;
    // 区划权限判断
    areaId = areaId.toString();
    let prefix = areaId;
    // 省
    if (areaId.endsWith("0000")) prefix = areaId.substring(0, 2);
    // 省
    if (areaId.endsWith("0000")) prefix = areaId.substring(0, 2);
    // 市
    else if (areaId.endsWith("00")) prefix = areaId.substring(0, 4);
    sourceList = res.data
      .filter((item) => item.level >= 3) // 过滤掉中国
      .filter((item) => item.areaId) // 过滤掉没有aeraId的数据
      .map((item) => ({
        ...item,
        unused:
          areaId == 100000
            ? false
            : !item.areaId.toString().startsWith(prefix), // 地区权限判断
      }));

    const mines = sourceList.filter((item) => item.level == 4);
    treeData.value = proxy.handleTree(sourceList);
    nextTick(()=>{
      mineClick(mines[0]);
    })
  }).finally(() => {
    loading.value = false;
  });
};

// 地区筛选
const filterNode = (value,data) => {
  if (!value) return true
  return data.areaName.includes(value)
}

const show = () => {
  dialogVisible.value = true;
  loadTree();
};
// 矿树点击事件
function mineClick(mine) {
  getMineInfoById(mine.id).then(res=>{
    if (res.code == 200) {
      queryParams.value.openPitNo = res.data.openPitNo
      getMonitorList()
    }
  })
}
// 查询视频接口
function getMonitorList() {
  // 先销毁所有实例
  if (flvPlayers.value.length > 0) {
    flvPlayers.value.forEach(player=>{
      player.destroy()
    })
  }
  flvPlayers.value = []
  getMonitorByMine(queryParams.value).then(monitor=>{
    if (monitor.code == 200) {
      total.value = monitor.total
      videoList.value = monitor.rows
      nextTick(()=>{
        videoList.value.forEach(item=>{
          initVideoPlayer(item.id, item.videoUrl)
        })
      })
    }
  })
}
// 切换页函数
const onPagechange = (currentPage, pageSize) => {
  queryParams.value.pageNum = currentPage;
  queryParams.value.pageSize = pageSize;
  getMonitorList();
};
// 初始化视频播放器
function initVideoPlayer(videoId, videoUrl) {
  const videoElement = document.getElementById(videoId);
  if (!videoElement) {
    console.error(`未找到ID为${videoId}的视频元素`);
    return;
  }
  if (flvjs.isSupported()) {
    // 创建flv播放器
    const flvPlayer = flvjs.createPlayer({
      type: "flv",
      url: videoUrl,
      isLive: true,
      hasAudio: false,
      hasVideo: true,
      cors: true,
    });

    flvPlayer.attachMediaElement(videoElement);
    flvPlayer.load();
    flvPlayer.play();

    console.log("FLV播放器已加载，尝试播放...");

    // 添加更多事件监听以便调试
    flvPlayer.on(flvjs.Events.LOADING_COMPLETE, () => {
      console.log(`${videoId} 加载完成`);
    });

    flvPlayer.on(flvjs.Events.MEDIA_INFO, (mediaInfo) => {
    });

    // 存储播放器实例
    flvPlayers.value.push(flvPlayer);

    // 添加事件监听
    videoElement.addEventListener("play", () => {
    });

    videoElement.addEventListener("pause", () => {
      console.log(`${videoId} 暂停播放`);
    });

    videoElement.addEventListener("error", (e) => {
      console.error(`${videoId} 视频元素错误:`, e);
    });
  } else {
    console.error("您的浏览器不支持FLV.js");
  }
};
// 关闭窗口时销毁player
function closeDialog() {
  if (flvPlayers.value.length > 0) {
    flvPlayers.value.forEach(player=>{
      player.destroy()
    })
  }
  flvPlayers.value = []
}

defineExpose({
  show,
});
</script>

<style lang="scss" scoped>
.tree-content {
  height: 420px;
  overflow: auto;
  ::v-deep(.el-tree) {
    background: transparent;
    color: #fff;

    --el-tree-node-content-height: 30px;

    .el-tree-node__content:hover {
      background-color: rgba(0, 0, 0, 0.15);
    }

    .el-tree-node:focus > .el-tree-node__content {
      background-color: rgba(31, 198, 255, 0.35);
    }

    .el-checkbox__inner {
      background-color: rgba(0, 12, 50, 1);
      // border: 1px solid #196590 !important;
    }

    // .is-current {
    //   .el-tree-node__content {
    //     background-color: rgba(31, 198, 255, 0.35);
    //   }
    // }
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;

    .node-text {
      width: 100%;
      white-space: nowrap;
      /* 文字不换行 */
      overflow: hidden;
      /* 溢出部分隐藏 */
      text-overflow: ellipsis;
      /* 显示省略号 */
    }

    .btn {
      color: #9cfefe;
      border: 1px solid #1fc6ff7d;
      background-color: rgb(156 254 254 / 15%);
      // padding: 1px 6px;
      width: 40px;
      text-align: center;
      border-radius: 2px;
    }

    .btn:hover {
      cursor: pointer;
    }
  }
}
.video-div {
  width: 100%;
  height: 400px;
  .video-child {
    position: relative;
    .video-child-name {
      position: absolute;
      top: 5px;
      left: 10px;
      color: #fff;
      z-index: 999;
    }
  }
}
.page-div {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
